class SqlOrderController < ApplicationController

  def index
    @db_names = Database.select(:dbname,:common_name).group(:dbname,:common_name)
  end

  def show
    @db_name = Database.find_by_dbname(params[:db_name])
    @db_envs = Database.select(:id,:env).where("dbname = ?",params[:db_name]).order(id: :desc)
  end

  def new
    if (!params[:sql_script] || params[:sql_script].strip.empty?)
      @sql_script_error = true
    end
    if (!params[:title] || params[:title].strip.empty?)
      @title_error = true
    end
    if (@sql_script_error || @title_error)
      redirect_to '/sql_order/' + params[:db_name]
      return
    end
    db_name = Database.find(params[:database_id])
    sql_order = current_user.sql_orders.new
    sql_order.database_id = db_name.id
    sql_order.status = 'submitted'
    sql_order.title = params[:title]
    sql_order.user_id = current_user.id
    sql_content = sql_order.build_sql_content
    sql_content.script = params[:sql_script]
    sql_order.save
    start_sql_order(sql_order)
    redirect_to sql_history_path
  end


  def start_sql_order(sql_order)
    check_sql(sql_order.id)
  end

  def file_new
    @db_name = Database.find_by_dbname(params[:db_name])
    @db_envs = Database.select(:id,:env).where("dbname = ?",params[:db_name]).order(id: :desc)
  end

  def upload
    file_upload_io = params[:filename]
    File.open(Rails.root.join('public', 'uploads', file_upload_io.original_filename), 'wb') do |file|
      file.write(file_upload_io.read)
    end
    db_name = Database.find(params[:database_id])
    upload_file = current_user.sql_orders.new
    upload_file.database_id = db_name.id
    upload_file.status = 'fileupload'
    upload_file.title = params[:title]
    upload_file.user_id = current_user.id
    sql_content = upload_file.build_sql_content
    sql_content.script = file_upload_io.original_filename
    upload_file.save
    file_upload_order(upload_file)
    redirect_to sql_history_path
  end

  def file_upload_order(upload_file)
    check_file(upload_file.id)
  end

end
